# V2.0.0
import sys
import time
import random
import traceback
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import Core
import sys

# 检查是否提供了足够的参数
# len(sys.argv) 是参数的总个数（包括脚本名）
if len(sys.argv) < 2:
    print("错误：请提供 name 参数")
    print("用法：python a.py <name>")
    # 非零退出码通常表示错误
    sys.exit(1) 

# 获取第一个参数（在脚本名之后）
keyword = sys.argv[1]
print(f"你好, {keyword}!")
try:
    ilog = Core.Logger("taobao")
    bot_gui = Core.Gui("淘宝")

    # 读取配置文件
    with open("config.json", "r") as f:
        config = json.load(f)
    default_output_formats = config.get("output_format", ["csv", "json"])  # 默认 CSV 和 JSON

    # 获取商品关键词
    # bot_gui.set_text("请输入商品关键词", bot_gui.COLOR_ATTENTION)
    # keyword = bot_gui.ask_string("请输入商品关键词", "输入商品关键词")
    # if len(keyword) < 1:
    #     bot_gui.set_text("ERROR：商品关键词为空", bot_gui.COLOR_ERROR)
    #     ilog.write_error("商品关键词为空请检查您的输入.", dialog=True)
    #     sys.exit(1)

    # 获取用户选择的输出格式
    # bot_gui.set_text("请选择输出格式", bot_gui.COLOR_ATTENTION)
    # output_formats = bot_gui.ask_output_formats(default_formats=default_output_formats)
    # ilog.write_info(f"用户选择的输出格式: {output_formats}")
    # print(f"用户选择的输出格式: {output_formats}")

    # 初始化浏览器
    bot_gui.set_text("程序正在准备", bot_gui.COLOR_DEFAULT)
    bot_gui.set_status("正在初始化输出文件...")
    # 初始化写入器
    output_formats=['xlsx']
    writers = {}
    if "csv" in output_formats:
        writers["csv"] = Core.CsvWriter(keyword, "taobao")
    if "json" in output_formats:
        writers["json"] = Core.JsonWriter(keyword, "taobao")
    if "xlsx" in output_formats:
        writers["xlsx"] = Core.ExcelWriter(keyword, "taobao")
    if "txt" in output_formats:
        writers["txt"] = Core.TxtWriter(keyword, "taobao")
    if "sql" in output_formats:
        writers["sql"] = Core.SqlWriter(keyword, "taobao")

    browser = Core.BrowserControl(Core.pre_check_configFile(), bot_gui, ilog)
    # 注入Cookie
    browser.navi_to("https://www.taobao.com")
    browser.inject_cookie("taobao")
    # 发起搜索
    bot_gui.set_text("发起搜索")
    browser.navi_to(f"https://s.taobao.com/search?page=1&q={keyword}&tab=all")
    page_total = browser.find_element_css(
        "#sortBarWrap_right > div > div > div.next-pagination.next-small.next-simple.next-no-border > div > span"
    ).text
    page_total = page_total.split("/").pop()
    # bot_gui.set_text("范围设定", bot_gui.COLOR_ATTENTION)
    # bot_gui.set_status(f"共计{page_total}页,请在弹出的窗口中输入范围")
    # page_start = int(
    #     bot_gui.ask_string("爬取范围设定 - 开始页数", f"输入爬取范围的开始页数,最小值1")
    # )
    # page_end = int(
    #     bot_gui.ask_string(
    #         "爬取范围设定 - 结束页数", f"输入爬取范围的结束页数,最大页数为{page_total}"
    #     )
    # )
    page_start=1
    page_end = 2
    ilog.write_info(f"spider search range:{page_start}->{page_end} total:{page_total}")
    # 设置合理的等待超时
    WAIT_TIMEOUT = 10
    SHORT_WAIT = 1
    for page in range(page_start, page_end + 1):
        try:
            bot_gui.set_text("正在运行", bot_gui.COLOR_RUNNING)
            try:
                browser.find_element_css(
                    "#search-content-leftWrap > div.leftContent--BdYLMbH8 > div.pgWrap--RTFKoWa6 > div > div > span.next-input.next-medium.next-pagination-jump-input > input"
                ).send_keys(page, Keys.ENTER)
            except Exception as e:
                raise Exception(f"前往页失败:P{page} - {e}")

            bot_gui.set_progress(page - page_start, page_end - page_start + 1)
            # 使用更智能的等待方式而不是固定延时
            time.sleep(SHORT_WAIT)  # 短暂等待确保完全加载
            browser.scroll_page_end()
            goods_array = browser.browser.find_elements(
                By.CSS_SELECTOR, "#content_items_wrapper>div"
            )
            for index, good in enumerate(goods_array):
                bot_gui.set_status(f"正在保存商品数据...{index}/{len(goods_array)}")
                try:
                    data = {}
                    data["item_link"] = browser.find_element_css(
                        "a", good
                    ).get_attribute("href")
                    data["item_name"] = browser.find_element_css(
                        "a> div > div.mainPicAndDesc--Q5PYrWux > div.descWrapper--Ta96FeyX.adaptMod--k5rdyVB_ > div > span",
                        good,
                    ).text
                    data["item_price"] = browser.find_element_css(
                        "a > div > div.mainPicAndDesc--Q5PYrWux > div.priceWrapper--dBtPZ2K1.adaptMod--uU2wpGzc > div > div.innerPriceWrapper--aAJhHXD4",
                        good,
                    ).text
                    # data["item_image"] = browser.find_element_css(
                    #     "a> div > div.mainPicAndDesc--Q5PYrWux > div.mainPicAdaptWrapper--V_ayd2hD > img",
                    #     good,
                    # ).get_attribute("src")
                    data["item_image"]=""
                    data["item_rates"] = "-"
                    # data["item_shop"] = browser.find_element_css(
                    #     "a > div > div.shopInfo--Kmh31boz.adaptMod--JjSKtdhD > div.TextAndPic--grkZAtsC > a > div > span.shopNameText--DmtlsDKm",
                    #     good,
                    # ).text
                    data["item_shop"]=""
                    data["shop_link"] =""
                    # data["shop_link"] = browser.find_element_css(
                    #     "a > div > div.shopInfo--Kmh31boz.adaptMod--JjSKtdhD > div.TextAndPic--grkZAtsC > a",
                    #     good,
                    # ).get_attribute("href")
                    # 保存到所有配置的格式
                    for format_type, writer in writers.items():
                        writer.write_new_line(data)
                except Exception as e:
                    ilog.write_error(f"获取单个商品信息时出错:{e}")
            # bot_gui.set_text("正在延时", bot_gui.COLOR_DEFAULT)
            # browser.setTimeout(random.randint(1, 2), "反机器人验证")

        except:
            bot_gui.set_text(
                f"在爬取页面{page}时异常.\n如有人机验证请验证", bot_gui.COLOR_ERROR
            )
            ilog.write_error(f"在爬取页面{page}时异常.\n如有人机验证请验证", True)
            browser.setTimeout(20, "异常,可能您正在操作人机验证")
        if page % 5 == 0:  # 每5页稍微休息一下
                time.sleep(random.uniform(1, 3))
        else:
            time.sleep(random.uniform(0.5, 1.5))
    ilog.write_info("Spider Successful")
    bot_gui.set_text("程序结束!", bot_gui.COLOR_ATTENTION)
    bot_gui.set_status("正在进行最后处理,请稍后...")
    # 关闭所有写入器
    for format_type, writer in writers.items():
        if format_type == "csv":
            writer.close_csv()
        elif format_type == "json":
            writer.close_json()
        elif format_type == "xlsx":
            writer.close_excel()
        elif format_type == "txt":
            writer.close_txt()
        elif format_type == "sql":
            writer.close_sql()
    browser.exit()
    ilog.write_info("Exit...")
    bot_gui.set_text("即将退出", bot_gui.COLOR_DEFAULT)
    browser.setTimeout(5, "保存文件完成,即将退出...")
    sys.exit(0)

except Exception as e:
    print(f"未捕获的错误:{e}")
    print(traceback.format_stack())
    input("---Error---")
    